package com.bbex.service.impl;

import com.bbex.entity.UserCoinVolumeBill;
import com.bbex.entity.UserCoinVolumeBillHistory;
import com.bbex.service.UserCoinVolumeBillHistoryService;
import com.bbex.service.UserCoinVolumeBillService;
import com.bbex.service.UserCoinVolumeBillTaskService;
import com.bbex.util.Splitter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * UserCoinVolumeBillTaskServiceImpl.
 * <p>
 * <p>
 * 19-1-3下午6:04
 *
 * @author chenbin sixh
 */
@Component
public class UserCoinVolumeBillTaskServiceImpl implements UserCoinVolumeBillTaskService {

    @Autowired
    private UserCoinVolumeBillService billService;

    @Autowired
    private UserCoinVolumeBillHistoryService billHistoryService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public long execute() {
        LocalDateTime currentDateTime = LocalDateTime.now();
        int byHistoryCount = billService.findByHistoryCount(currentDateTime);
        int adverb = byHistoryCount / 1000;
        if (adverb == 0) {
            adverb = 1;
        }
        List<Splitter.Entry> pages = Splitter.baseSplitter(adverb, byHistoryCount);
        for (Splitter.Entry page : pages) {
            List<UserCoinVolumeBill> byHistory = billService.findByHistory(currentDateTime, page.pageStartRow, page.count);
            int size = byHistory != null ? byHistory.size() : 0;
            if (size > 0) {
                List<UserCoinVolumeBillHistory> collect = byHistory.stream().map(e -> {
                    UserCoinVolumeBillHistory history = new UserCoinVolumeBillHistory();
                    BeanUtils.copyProperties(e, history);
                    return history;
                }).collect(Collectors.toList());
                billHistoryService.batchInsert(collect);
            }
        }
        billService.deleteHistory(currentDateTime);
        return byHistoryCount;
    }
}
